package cmd

import (
	"errors"
	"github.com/spf13/cobra"
	"go.uber.org/zap"
	"strings"
	"vpom_-system/cmd/commends_of_sql"
	"vpom_-system/global"
)

const (
	MODE_SQL_Ctreate = iota + 1 // 创建表
	MODE_SQL_Import             // 导入数据
	Mode_SQL_Export             // 导出数据
)

var sqlMode int8

var sqlDesc = strings.Join([]string{
	"该子命令支持sql的初始化，功能如下:",
	"子命令的信息帮助查询例子: vpom sql m=1 (执行功能1建表)",
	"1: 创建数据库的表",
	"2: 导出数据库表的数据，生成sql",
	"3: 导入数据库表的信息",
}, "\n")

var SqlCmd = &cobra.Command{
	Use:   "sql",
	Short: "数据库初始化命令",
	Long:  sqlDesc,
	Run:   SqlRunServer,
}

func SqlRunServer(cmd *cobra.Command, args []string) {
	switch sqlMode {
	case MODE_SQL_Ctreate:
		if err := commends_of_sql.SQL(); err != nil {
			global.Log.Error("Generate SQL file failed", zap.Error(err))
			return
		} else {
			global.Log.Info("Generate SQL file successfully")
		}
	case MODE_SQL_Import:
		if err := commends_of_sql.SQLExport(); err != nil {
			global.Log.Error("Export SQL file failed", zap.Error(err))
		} else {
			global.Log.Info("Export SQL file successfully")
		}
	case Mode_SQL_Export:
		if errs := commends_of_sql.SQLImport(cmd.Name()); len(errs) > 0 {
			var combinedErrors string
			for _, err := range errs {
				combinedErrors += err.Error() + "\n"
			}
			err := errors.New(combinedErrors)
			global.Log.Error("Failed to import SQL data:", zap.Error(err))
		} else {
			global.Log.Info("Import SQL data successfully")
		}
	default:
		err := cmd.Help()
		global.Log.Error("Invalid command usage", zap.Error(err))
	}
}

func init() {
	// 设置子命令的flag
	SqlCmd.Flags().Int8VarP(&sqlMode, "mode", "m", 0, "选择sql执行功能，eg: vpom sql -m=1 (执行对应功能)")

}
